package com.hundsun.yr.universal.p2p.presenter.impl;

import android.content.Context;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;

import com.hundsun.mobile.zwgt.R;
import com.hundsun.yr.universal.library.data.HSSharedPreferences;
import com.hundsun.yr.universal.library.netstatus.NetUtils;
import com.hundsun.yr.universal.library.widget.HSToast;
import com.hundsun.yr.universal.p2p.bean.AdSlideBeen;
import com.hundsun.yr.universal.p2p.bean.MyInvestBeen;
import com.hundsun.yr.universal.p2p.bean.MyLoanListBeen;
import com.hundsun.yr.universal.p2p.bean.UserInfo;
import com.hundsun.yr.universal.p2p.config.Config;
import com.hundsun.yr.universal.p2p.config.Constants;
import com.hundsun.yr.universal.p2p.config.TaskConstants;
import com.hundsun.yr.universal.p2p.interactor.base.RequestInteractor;
import com.hundsun.yr.universal.p2p.interactor.impl.StringRequestGetInteractorImpl;
import com.hundsun.yr.universal.p2p.interactor.impl.StringRequestInteractorImpl;
import com.hundsun.yr.universal.p2p.listener.BaseMultiLoadedListener;
import com.hundsun.yr.universal.p2p.presenter.base.RequestPresenter;
import com.hundsun.yr.universal.p2p.utils.AndroidDes3Util;
import com.hundsun.yr.universal.p2p.utils.GsonTool;
import com.hundsun.yr.universal.p2p.utils.Logs;
import com.hundsun.yr.universal.p2p.view.base.BaseListView;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;


/**
 * @version V1.0
 * @Title: BaseListPresenterImpl.java
 * @Description: TODO(用一句话描述该文件做什么)
 * @date 2015-10-27 上午11:18:59
 * @author:hejun.shen
 * @email:shenhj15971@hundsun.com
 * @replace author:
 * @replace date:
 */
public class BaseListPresenterImpl implements RequestPresenter, BaseMultiLoadedListener<String>, OnClickListener {

    private Context mContext = null;
    private BaseListView mBaseView = null;
    private RequestInteractor mInteractor = null;
    private RequestInteractor mInteractor2 = null;
    /**
     * list的key
     **/
    private String mKey;
    /**
     * 任务名
     **/
    private String mTask_name;
    /**
     * 请求地址
     **/
    private String mUrl;
    /**
     * 加载事件
     **/
    private int mEvent_tag;
    /**
     * 参数
     **/
    private HashMap<String, String> mParams;
    /**
     * 是否刷新
     **/
    private boolean mIsSwipeRefresh;
    /**
     * 用户信息sp文件
     **/
    private HSSharedPreferences sharedPreferences = null;

    public BaseListPresenterImpl(Context context, BaseListView baseView, String key) {
        // TODO Auto-generated constructor stub
        if (null == baseView) {
            throw new IllegalArgumentException("Constructor's parameters must not be Null");
        }
        this.mContext = context;
        this.mBaseView = baseView;
        this.mInteractor = new StringRequestInteractorImpl(this);
        this.mInteractor2 = new StringRequestGetInteractorImpl(this);
        this.mKey = key;
        this.sharedPreferences = new HSSharedPreferences(context, Config.SPPath.file_userLoginedInfo);
    }

    @Override
    public void onSuccess(String task_name, int event_tag, String data) {
        //网络请求成功，进度条消失
        Logs.e("baselistpresenterimpl data: " + data);
        mBaseView.hideLoading();
        mBaseView.closeProgress();//请求数据成功
        //对数据进行处理
        try {
            AdSlideBeen adSlideBeen = (AdSlideBeen) GsonTool.getInstanceByJson(AdSlideBeen.class, data);
            switch (task_name) {
                case TaskConstants.INVERST_LIST://我的投资
                    switch (adSlideBeen.code) {
                        case Constants.REQUESTCODE_000000:
                            //请求成功，对数据进行解密
                            try {
                                String decode = AndroidDes3Util.decode(adSlideBeen.data, sharedPreferences.getShareProf(UserInfo.TOKENID).substring(0, 24), (Date.parse(adSlideBeen.timestamp) + "").substring((Date.parse(adSlideBeen.timestamp) + "").length() - 8, (Date.parse(adSlideBeen.timestamp) + "").length()));
                                String[] split = decode.split("\\n");
                                Logs.e("bpiINVERST_LIST:77777" + decode);
                                ArrayList<MyInvestBeen> invests = GsonTool.jsonToArrayList(split[1], MyInvestBeen.class);
                                //对数据进行解析
                                if (event_tag == Constants.EVENT_REFRESH_DATA) {
                                    //event_tag为刷新界面
                                    if (invests.size() > 0) {
                                        mBaseView.refreshListData(invests);
                                    } else {
                                        mBaseView.refreshListData(null);
                                        //没有数据显示空页面
                                        mBaseView.showEmpty(0, mContext.getString(R.string.empty_msg), this);
                                    }
                                } else if (event_tag == Constants.EVENT_LOAD_MORE_DATA) {
                                    mBaseView.addMoreListData(invests);
                                }
                            } catch (Exception e) {
                                new HSToast(mContext).getSingleLongToast(mContext.getString(R.string.date_error)).show();
                                e.printStackTrace();
                            }
                            break;
                        case Constants.REQUESTCODE_100600:
                            mBaseView.onFailure(TaskConstants.INVERST_LIST);
                            new HSToast(mContext).getSingleLongToast(adSlideBeen.msg).show();
                            break;
                        case Constants.REQUESTCODE_100020:
                            mBaseView.onFailure(TaskConstants.INVERST_LIST);
                            //Header值为空--不做任何提示
                            break;
                        case Constants.REQUESTCODE_100010:
                            mBaseView.onFailure(TaskConstants.INVERST_LIST);
                            break;
                        default:
                            mBaseView.onFailure(TaskConstants.INVERST_LIST);
                            new HSToast(mContext).getSingleLongToast(adSlideBeen.msg).show();
                            mBaseView.showError(adSlideBeen.msg, this);
                            break;
                    }
                    break;
                case TaskConstants.LOAN_LIST://我的借款
                    switch (adSlideBeen.code) {
                        case Constants.REQUESTCODE_000000:
                            //请求成功，对数据进行解密
                            try {
                                String decode = AndroidDes3Util.decode(adSlideBeen.data, sharedPreferences.getShareProf(UserInfo.TOKENID).substring(0, 24), (Date.parse(adSlideBeen.timestamp) + "").substring((Date.parse(adSlideBeen.timestamp) + "").length() - 8, (Date.parse(adSlideBeen.timestamp) + "").length()));
                                String[] split = decode.split("\\n");
                                ArrayList<MyLoanListBeen> loanLists = GsonTool.jsonToArrayList(split[1], MyLoanListBeen.class);

                                //对数据进行解析
                                if (event_tag == Constants.EVENT_REFRESH_DATA) {
                                    //event_tag为刷新界面
                                    if (loanLists.size() > 0) {
                                        mBaseView.refreshListData(loanLists);
                                    } else {
                                        mBaseView.refreshListData(null);
                                        //没有数据显示空页面
                                        mBaseView.showEmpty(0, mContext.getString(R.string.empty_msg), this);
                                    }
                                } else if (event_tag == Constants.EVENT_LOAD_MORE_DATA) {
                                    mBaseView.addMoreListData(loanLists);
                                }
                            } catch (Exception e) {
                                new HSToast(mContext).getSingleLongToast(mContext.getString(R.string.date_error)).show();
                                e.printStackTrace();
                            }
                            break;

                        case Constants.REQUESTCODE_100600:
                            mBaseView.onFailure(TaskConstants.LOAN_LIST);
                            new HSToast(mContext).getSingleLongToast(adSlideBeen.msg).show();
                            break;
                        case Constants.REQUESTCODE_100020:
                            mBaseView.onFailure(TaskConstants.LOAN_LIST);
                            //Header值为空--不做任何提示
                            break;
                        case Constants.REQUESTCODE_100010:
                            mBaseView.onFailure(TaskConstants.LOAN_LIST);
                            break;
                        default:
                            mBaseView.onFailure(TaskConstants.LOAN_LIST);
                            new HSToast(mContext).getSingleLongToast(adSlideBeen.msg).show();
                            mBaseView.showError(adSlideBeen.msg, this);
                            break;
                    }
                    break;
            }
        } catch (Exception e) {
            new HSToast(mContext).getSingleLongToast(mContext.getString(R.string.date_error)).show();
            e.printStackTrace();
        }
    }

    @Override
    public void onException(String task_name, String msg) {
        // TODO Auto-generated method stub
        mBaseView.closeProgress();
        mBaseView.hideLoading();
        mBaseView.showError(msg, this);
        mBaseView.onFailure(task_name);
    }

    /***
     * header|params
     * @param task_name 任务名
     * @param url 请求地址
     * @param event_tag 加载事件{@link Constants}}
     * @param params 参数
     * @param isSwipeRefresh 是否刷新
     */
    @Override
    public void loadingData(String task_name, String url, int event_tag,
                            HashMap<String, String> params, boolean isSwipeRefresh) {

        if (event_tag == Constants.EVENT_REFRESH_DATA) {
            this.mTask_name = task_name;
            this.mUrl = url;
            this.mParams = params;
            this.mIsSwipeRefresh = isSwipeRefresh;
            this.mEvent_tag = event_tag;
        }

        mBaseView.hideLoading();
        if (event_tag == Constants.EVENT_PROGRESS) {
            mBaseView.showProgress("");
        }
        if (isSwipeRefresh) {
            mBaseView.showLoading(mContext.getString(R.string.common_loading_message));
        }
        if (NetUtils.isNetworkConnected(mContext)) {
            if (TextUtils.equals(task_name, TaskConstants.INVERST_LIST)) {
                mInteractor2.getRequestData(task_name, url, event_tag, params);
            } else if (TextUtils.equals(task_name, TaskConstants.LOAN_LIST)) {
                Logs.e("fengqingxia: loanlist");
                mInteractor2.getRequestData(task_name, url, event_tag, params);
            }
        } else {
            mBaseView.hideLoading();
            mBaseView.closeProgress();
            mBaseView.onFailure(task_name);
            mBaseView.showNetError(this);
        }
    }

    @Override
    public void loadingData(String task_name, String url, int event_tag, HashMap<String, String> params, HashMap<String, String> header, boolean isSwipeRefresh) {

    }

    @Override
    public void loadingData(String task_name, String url, int event_tag, JSONObject params, HashMap<String, String> header, boolean isSwipeRefresh) {

    }

    @Override
    public void initialized() {
        // TODO Auto-generated method stub

    }

    @Override
    public void onClick(View v) {
        loadingData(mTask_name, mUrl, mEvent_tag, mParams, mIsSwipeRefresh);
    }

}
